package com.prs.crm.action.hr;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.domain.hr.Dept;
import com.prs.crm.domain.hr.ShareEim;
//import com.prs.crm.domain.oa.CompanyMailList;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeCommon;
import com.prs.crm.domain.sys.SysDepartment;
import com.prs.crm.service.hr.DeptService;
import com.prs.crm.service.person.ShareEimService;
import com.prs.crm.service.sys.CodeCommonService;
import com.prs.crm.service.sys.CodeService;

public class DeptAction extends BaseAction {

	private static final long serialVersionUID = 4669677166507995583L;
	private DeptService deptService;
	private Dept dept;
	private PaginationSupport pagination;
	private Dept parentDept;
	private Collection<TreeNode> nodes;

	private CodeCommon codeCommon;
	private CodeCommonService codeCommonService;
	private String Encode;
	private Code code;
	private CodeService codeService;

	private Collection<CodeCommon> codelist;
	private Connection con;
	private Statement stmt;
	private ResultSet rs;
	private ResultSet rs1;
	private ResultSet rs2;
	private ResultSet rs3;
	private String fieldname;
	private ShareEimService shareEimService;
	private TreeNode root;
	private String ClassName;
	private String userName;
	private String userPass;
	private String url1;
	private String address;
	private String baseName;
	public TreeNode getRoot() {
		return root;
	}
	public void setRoot(TreeNode root) {
		this.root = root;
	}
	public ShareEimService getShareEimService() {
		return shareEimService;
	}
	public void setShareEimService(ShareEimService shareEimService) {
		this.shareEimService = shareEimService;
	}
	@Action("treeDept")
	public String treeDept() {
		this.codelist = this.getCodeCommonService().getCodeCommonByCodeType(
				"部门");
		return SUCCESS;
	}
   @Action("selectDept") 
   public String selectDept(){
	   return SUCCESS; 
	   }
	@Action(value = "loadDept", results = { @Result(name = "success", type = "json", params = {
			"root", "dept", "excludeProperties", "childs" }) })
	public String loadDept() {
		return SUCCESS;
	}

	@Action(value = "loadDeptTree", results = { @Result(name = "success", type = "json", params = {
			"root", "nodes" }) })
	public String loadDeptTree() {
		nodes = new ArrayList<TreeNode>();
		Collection<Dept> depts = this.getDeptService().getRootDepts();
		for (Dept dept : depts) {
			TreeNode node = new TreeNode();
			node.setId(dept.getId().toString());
			node.setText(dept.getName());
			nodes.add(node);
			addChildNode(dept, node);
		}
		return SUCCESS;
	}

	private void addChildNode(Dept parent, TreeNode parentNode) {
		if (parent.getChilds() != null) {
			for (Dept dept : parent.getChilds()) {
				TreeNode node = new TreeNode();
				node.setId(dept.getId().toString());
				node.setText(dept.getName());
				parentNode.addChildNode(node);
				addChildNode(dept, node);
			}
		}
	}

	@Action(value = "saveDept", results = {
			@Result(name = "success", type = "json", params = { "root", "dept",
					"excludeProperties", "childs,parent" }),
			@Result(name = "error", type = "chain", location = "treeDept") })
	public String saveDept() {
		try {
			if (dept.getName() == null || "".equals(dept.getName().trim())) {
				addActionError("名称不能为空");
				return ERROR;
			}
			if (dept.getDeptcode() == null
					|| "".equals(dept.getDeptcode().trim())) {
				addActionError("编码不能为空");
				return ERROR;
			}
			if (parentDept != null) {
				dept.setParent(parentDept);
			}

			if ("n".equals(Encode)) {
				Code codes = new Code();
				codes.setCodeValue(dept.getDeptcode());
				codes.setEntityName(this.getClass().getName());
				codes.setCodeType("手动编码");
				codes.setCodeMolde("部门");
				this.getCodeService().save(codes);
				dept.setCode(codes);
				dept.setState(1);
				this.getDeptService().save(dept);
				ShareEim se=this.getShareEimService().getCode("se01");
				if (se!=null) {
					if (se.getState().equals("true")) {
						this.saveEimDept(dept);
					}
				}
			} else {
				CodeCommon Vob = this.getCodeCommonService().getVobject(
				codeCommon.getId());
				Code codes = new Code();
				codes.setEntityName(this.getClass().getName());
				codes.setCodeValue(dept.getDeptcode());
				Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
				this.codeCommonService.saveOrUpdate(Vob);
				codes.setCodeType(Vob.getCodePlan());
				codes.setCodeMolde("部门");
				this.getCodeService().save(codes);
				dept.setCode(codes);
				dept.setState(1);
				this.getDeptService().save(dept);
			}
		} catch (Exception e) {
			// TODO: handle exception
			this.setDept(null);
		}
		
		return SUCCESS;
	}

	@Action(value = "removeDept", results = { @Result(name = "success", type = "json", params = {
			"root", "prompt" }) })
	public String removeDept() {
		try {
			this.getDeptService().remove(dept);
			this.setPrompt("success");
		} catch (Exception e) {
			// TODO: handle exception
			this.setPrompt("error");
		}
		return SUCCESS;
	}
	
	
	@Action(value = "loadDepartTree", results = { @Result(name = "success", type = "json", params = {
			"root", "root" }) })
	public String loadDepartTree() {
		root = new TreeNode();
		root.setId("-1");
		TreeNode firstNode = new TreeNode();
		firstNode.setId("0");
		firstNode.setText("部门选择");
		Collection<Dept> depts=this.getDeptService().getRootDepts();
		for (Dept dept : depts) {
			TreeNode node = new TreeNode();
			node.setText(dept.getName());
			node.setId("depart-" + dept.getId().toString());
			firstNode.addChildNode(node);
			addDepartNode(node, dept);
		}
		root.addChildNode(firstNode);
		return SUCCESS;
	}
	
	private void addDepartNode(TreeNode parent, Dept dept) {
		for (Dept depart : dept.getChilds()) {
			TreeNode node = new TreeNode();
			node.setText(depart.getName());
			node.setId("depart-" + depart.getId().toString());
			parent.addChildNode(node);
			addDepartNode(node, depart);	
		}
	}
	
	@Action("listDept")
	public String listDept(){
		DetachedCriteria criteria=this.getPaginationHelper().createQuery(Dept.class);
		pagination=this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getDeptService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	
	@Action("editShare")
	public String editShare(){		
		return SUCCESS;
	}

	@Action(value = "saveColumn", results = {
			@Result(name = "success", type = "redirect", location = "editShare?dept=${dept.getId()}"),
			@Result(name = "error", type = "chain", location = "editShare") })
	public String saveColumn() throws SQLException{
		dept.setAllfieldname("");
		this.getDeptService().submit(dept);
		Properties pro=new Properties();
		
		String path = Thread.currentThread().getContextClassLoader().getResource("connect.properties").getPath();
		try {
			pro.load(new FileInputStream(path));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String ClassName=pro.getProperty("ClassName");
		String userName=pro.getProperty("userName");
		String userPass=pro.getProperty("userPass");
		String url1=pro.getProperty("url1");
		try {
			Class.forName(ClassName);
			con = DriverManager.getConnection(url1, userName, userPass);
			stmt = this.con.createStatement();
			try{
				PreparedStatement pst = con.prepareStatement("select * from "+dept.getTableName());
				rs1=pst.executeQuery();
			}catch (Exception e) {
				this.addActionError("请确认表名是否输入正确");
				return ERROR;
			}
				
			ResultSetMetaData metaData = rs1.getMetaData();
			 if (rs1.next()) {
				 for (int i = 1; i <= metaData.getColumnCount(); i++) {
				    if (dept.getAllfieldname()==null || "".equals(dept.getAllfieldname().trim())) {
						 dept.setAllfieldname(metaData.getColumnName(i));
					}else{
						 dept.setAllfieldname(dept.getAllfieldname()+","+metaData.getColumnName(i));
					}
				    this.getDeptService().submit(dept);
				 } 	
			 }
			 rs1.close();
			 con.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	@Clew(results = { "success" })
	@Action(value = "saveShare", results = {
			@Result(name = "success", type = "redirect", location = "listDept"),
			@Result(name = "error", type = "chain", location = "editShare") })
	public String saveShare() throws SQLException{
		dept.setState(2);
		this.getDeptService().submit(dept);
		this.saveEimDept(dept);
		this.setPrompt("共享成功！");
		return SUCCESS;
	}
	@Action("viewDept")
	public String view() {
		return SUCCESS;
	}

	public DeptService getDeptService() {
		return deptService;
	}

	public void setDeptService(DeptService deptService) {
		this.deptService = deptService;
	}

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	public Dept getParentDept() {
		return parentDept;
	}

	public void setParentDept(Dept parentDept) {
		this.parentDept = parentDept;
	}

	public Collection<TreeNode> getNodes() {
		return nodes;
	}

	public void setNodes(Collection<TreeNode> nodes) {
		this.nodes = nodes;
	}

	public CodeCommon getCodeCommon() {
		return codeCommon;
	}

	public void setCodeCommon(CodeCommon codeCommon) {
		this.codeCommon = codeCommon;
	}

	public CodeCommonService getCodeCommonService() {
		return codeCommonService;
	}

	public void setCodeCommonService(CodeCommonService codeCommonService) {
		this.codeCommonService = codeCommonService;
	}

	public Code getCode() {
		return code;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeCommon> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeCommon> codelist) {
		this.codelist = codelist;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}
	
	public void saveEimDept(Dept dept) throws SQLException{
		ShareEim se=this.getShareEimService().getCode("se01");
		if (se!=null) {
			ClassName=se.getClassName();
			userName=se.getUserName();
			userPass=se.getUserPass();
			address=se.getIp();
			baseName=se.getBaseName();
			url1="jdbc:mysql://"+address+":3306/"+baseName;
		}
		try {
			Class.forName(ClassName);
			try {
				con = DriverManager.getConnection(url1, userName, userPass);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stmt = this.con.createStatement();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs=stmt.executeQuery("select * from hr_dept where name='"+dept.getName()+"'");
			if(rs.next()==false){
				String sql1 = "insert into hr_dept(name,deptcode) values ("+"'"+dept.getName()+"','"+dept.getDeptcode()+"')";
				stmt.executeUpdate(sql1);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			rs.close();
			con.close();
		}
	}
	public String getFieldname() {
		return fieldname;
	}
	public void setFieldname(String fieldname) {
		this.fieldname = fieldname;
	}
}
